<template>
  <div class="my-courses">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1>我的课程</h1>
        <p>管理你的学习进度，继续你的学习之旅</p>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><Reading /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.totalCourses }}</div>
            <div class="stat-label">已购课程</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><CircleCheck /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.completedCourses }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.studyHours }}</div>
            <div class="stat-label">学习时长</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><Trophy /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.certificates }}</div>
            <div class="stat-label">获得证书</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <div class="filter-bar">
        <div class="filter-left">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索课程..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="filter-right">
          <el-select v-model="selectedStatus" placeholder="学习状态" @change="handleFilter">
            <el-option label="全部状态" value="" />
            <el-option label="学习中" value="learning" />
            <el-option label="已完成" value="completed" />
            <el-option label="未开始" value="not_started" />
          </el-select>
          
          <el-select v-model="selectedCategory" placeholder="课程分类" @change="handleFilter">
            <el-option label="全部分类" value="" />
            <el-option label="前端开发" value="frontend" />
            <el-option label="后端开发" value="backend" />
            <el-option label="移动开发" value="mobile" />
            <el-option label="数据科学" value="data" />
          </el-select>
          
          <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort">
            <el-option label="最近学习" value="recent" />
            <el-option label="购买时间" value="purchase" />
            <el-option label="课程名称" value="name" />
            <el-option label="学习进度" value="progress" />
          </el-select>
        </div>
      </div>
    </div>

    <!-- 课程列表 -->
    <div class="courses-section">
      <div class="courses-grid">
        <div 
          v-for="course in filteredCourses" 
          :key="course.id"
          class="course-card"
        >
          <div class="course-image">
            <img :src="course.cover" :alt="course.title" />
            <div class="course-overlay">
              <el-button 
                circle 
                type="primary" 
                @click="continueLearning(course)"
              >
                <el-icon><VideoPlay /></el-icon>
              </el-button>
            </div>
            <div class="course-status">
              <el-tag 
                :type="getStatusType(course.status)" 
                size="small"
              >
                {{ getStatusText(course.status) }}
              </el-tag>
            </div>
          </div>
          
          <div class="course-content">
            <div class="course-category">{{ course.category }}</div>
            <h3 class="course-title">{{ course.title }}</h3>
            
            <div class="course-progress">
              <div class="progress-info">
                <span class="progress-text">学习进度</span>
                <span class="progress-percent">{{ course.progress }}%</span>
              </div>
              <el-progress 
                :percentage="course.progress" 
                :show-text="false"
                :stroke-width="6"
              />
            </div>
            
            <div class="course-meta">
              <div class="meta-item">
                <el-icon><Clock /></el-icon>
                <span>{{ course.studyTime }} / {{ course.totalTime }}</span>
              </div>
              <div class="meta-item">
                <el-icon><Calendar /></el-icon>
                <span>{{ formatDate(course.lastStudyTime) }}</span>
              </div>
            </div>
            
            <div class="course-actions">
              <el-button 
                type="primary" 
                @click="continueLearning(course)"
                :disabled="course.status === 'completed'"
              >
                {{ course.status === 'completed' ? '已完成' : '继续学习' }}
              </el-button>
              
              <el-dropdown @command="handleAction">
                <el-button circle>
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="`detail-${course.id}`">
                      <el-icon><View /></el-icon>
                      课程详情
                    </el-dropdown-item>
                    <el-dropdown-item :command="`download-${course.id}`">
                      <el-icon><Download /></el-icon>
                      下载资料
                    </el-dropdown-item>
                    <el-dropdown-item :command="`certificate-${course.id}`" v-if="course.status === 'completed'">
                      <el-icon><Medal /></el-icon>
                      查看证书
                    </el-dropdown-item>
                    <el-dropdown-item :command="`review-${course.id}`" v-if="course.status === 'completed'">
                      <el-icon><Star /></el-icon>
                      评价课程
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-if="filteredCourses.length === 0" class="empty-state">
        <EmptyState
          image="/images/empty-courses.svg"
          title="暂无课程"
          description="你还没有购买任何课程，去发现更多精彩内容吧！"
        >
          <el-button type="primary" @click="goToCourseList">
            浏览课程
          </el-button>
        </EmptyState>
      </div>
    </div>

    <!-- 学习计划 -->
    <div class="study-plan-section">
      <div class="section-header">
        <h2>学习计划</h2>
        <el-button @click="createStudyPlan">
          <el-icon><Plus /></el-icon>
          创建计划
        </el-button>
      </div>
      
      <div class="study-plans">
        <div 
          v-for="plan in studyPlans" 
          :key="plan.id"
          class="plan-card"
        >
          <div class="plan-header">
            <h4>{{ plan.title }}</h4>
            <el-tag :type="plan.status === 'active' ? 'success' : 'info'" size="small">
              {{ plan.status === 'active' ? '进行中' : '已完成' }}
            </el-tag>
          </div>
          
          <div class="plan-progress">
            <div class="progress-info">
              <span>{{ plan.completedCourses }} / {{ plan.totalCourses }} 门课程</span>
              <span>{{ plan.progress }}%</span>
            </div>
            <el-progress 
              :percentage="plan.progress" 
              :show-text="false"
              :stroke-width="4"
            />
          </div>
          
          <div class="plan-actions">
            <el-button size="small" @click="viewPlan(plan)">查看详情</el-button>
            <el-button size="small" type="primary" @click="continuePlan(plan)">
              继续学习
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Reading, CircleCheck, Clock, Trophy, Search, VideoPlay,
  Calendar, MoreFilled, View, Download, Medal, Star, Plus
} from '@element-plus/icons-vue'
import EmptyState from '@/components/global/EmptyState.vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const selectedStatus = ref('')
const selectedCategory = ref('')
const sortBy = ref('recent')

// 统计数据
const stats = ref({
  totalCourses: 12,
  completedCourses: 5,
  studyHours: '156h',
  certificates: 3
})

// 我的课程数据
const myCourses = ref([
  {
    id: 1,
    title: 'Vue3 + TypeScript 实战开发',
    category: '前端开发',
    cover: '/images/course-vue3.jpg',
    progress: 75,
    status: 'learning',
    studyTime: '15h',
    totalTime: '20h',
    lastStudyTime: new Date('2024-01-15'),
    purchaseTime: new Date('2024-01-01')
  },
  {
    id: 2,
    title: 'React 18 新特性详解',
    category: '前端开发',
    cover: '/images/course-react.jpg',
    progress: 100,
    status: 'completed',
    studyTime: '15h',
    totalTime: '15h',
    lastStudyTime: new Date('2024-01-10'),
    purchaseTime: new Date('2023-12-15')
  },
  {
    id: 3,
    title: 'Node.js 后端开发实战',
    category: '后端开发',
    cover: '/images/course-nodejs.jpg',
    progress: 30,
    status: 'learning',
    studyTime: '8h',
    totalTime: '25h',
    lastStudyTime: new Date('2024-01-12'),
    purchaseTime: new Date('2024-01-05')
  }
])

// 学习计划数据
const studyPlans = ref([
  {
    id: 1,
    title: '前端工程师成长路径',
    status: 'active',
    completedCourses: 3,
    totalCourses: 8,
    progress: 38
  },
  {
    id: 2,
    title: '全栈开发者路径',
    status: 'active',
    completedCourses: 1,
    totalCourses: 12,
    progress: 8
  }
])

// 计算属性
const filteredCourses = computed(() => {
  let filtered = myCourses.value

  // 搜索筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(course => 
      course.title.toLowerCase().includes(keyword) ||
      course.category.toLowerCase().includes(keyword)
    )
  }

  // 状态筛选
  if (selectedStatus.value) {
    filtered = filtered.filter(course => course.status === selectedStatus.value)
  }

  // 分类筛选
  if (selectedCategory.value) {
    filtered = filtered.filter(course => course.category === selectedCategory.value)
  }

  // 排序
  switch (sortBy.value) {
    case 'recent':
      filtered.sort((a, b) => new Date(b.lastStudyTime) - new Date(a.lastStudyTime))
      break
    case 'purchase':
      filtered.sort((a, b) => new Date(b.purchaseTime) - new Date(a.purchaseTime))
      break
    case 'name':
      filtered.sort((a, b) => a.title.localeCompare(b.title))
      break
    case 'progress':
      filtered.sort((a, b) => b.progress - a.progress)
      break
  }

  return filtered
})

// 方法
const getStatusType = (status) => {
  const types = {
    'learning': 'warning',
    'completed': 'success',
    'not_started': 'info'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    'learning': '学习中',
    'completed': '已完成',
    'not_started': '未开始'
  }
  return texts[status] || '未知'
}

const formatDate = (date) => {
  const now = new Date()
  const diff = now - date
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) {
    return '今天'
  } else if (days === 1) {
    return '昨天'
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleFilter = () => {
  // 筛选逻辑已在计算属性中处理
}

const handleSort = () => {
  // 排序逻辑已在计算属性中处理
}

const continueLearning = (course) => {
  if (course.status === 'completed') {
    ElMessage.info('课程已完成')
    return
  }
  
  router.push(`/classroom/study/${course.id}`)
}

const handleAction = (command) => {
  const [action, courseId] = command.split('-')
  const course = myCourses.value.find(c => c.id === parseInt(courseId))
  
  switch (action) {
    case 'detail':
      router.push(`/classroom/course/${courseId}`)
      break
    case 'download':
      ElMessage.success('开始下载课程资料')
      break
    case 'certificate':
      ElMessage.success('查看课程证书')
      break
    case 'review':
      ElMessage.success('打开评价页面')
      break
  }
}

const goToCourseList = () => {
  router.push('/classroom/courses')
}

const createStudyPlan = () => {
  ElMessage.success('创建学习计划功能开发中')
}

const viewPlan = (plan) => {
  ElMessage.success(`查看学习计划：${plan.title}`)
}

const continuePlan = (plan) => {
  ElMessage.success(`继续学习计划：${plan.title}`)
}

onMounted(() => {
  // 初始化数据
})
</script>

<style lang="scss" scoped>
.my-courses {
  min-height: 100vh;
  background: var(--el-bg-color-page);
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
  
  .header-content {
    h1 {
      font-size: 28px;
      font-weight: 700;
      color: var(--el-text-color-primary);
      margin-bottom: 8px;
    }
    
    p {
      font-size: 16px;
      color: var(--el-text-color-secondary);
      margin: 0;
    }
  }
}

.stats-section {
  margin-bottom: 30px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  display: flex;
  align-items: center;
  gap: 16px;
  
  .stat-icon {
    width: 48px;
    height: 48px;
    background: var(--el-color-primary-light-9);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .el-icon {
      font-size: 24px;
      color: var(--el-color-primary);
    }
  }
  
  .stat-content {
    .stat-number {
      font-size: 24px;
      font-weight: 700;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }
    
    .stat-label {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
  }
}

.filter-section {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  margin-bottom: 30px;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
  
  @media (max-width: 768px) {
    flex-direction: column;
    align-items: stretch;
  }
}

.filter-left {
  .el-input {
    width: 300px;
    
    @media (max-width: 768px) {
      width: 100%;
    }
  }
}

.filter-right {
  display: flex;
  gap: 12px;
  
  @media (max-width: 768px) {
    flex-direction: column;
  }
  
  .el-select {
    width: 140px;
    
    @media (max-width: 768px) {
      width: 100%;
    }
  }
}

.courses-section {
  margin-bottom: 40px;
}

.courses-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
}

.course-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  }
}

.course-image {
  position: relative;
  height: 200px;
  overflow: hidden;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .course-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
  }
  
  &:hover .course-overlay {
    opacity: 1;
  }
  
  .course-status {
    position: absolute;
    top: 12px;
    right: 12px;
  }
}

.course-content {
  padding: 20px;
}

.course-category {
  font-size: 12px;
  color: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
  padding: 4px 8px;
  border-radius: 4px;
  display: inline-block;
  margin-bottom: 12px;
}

.course-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
  color: var(--el-text-color-primary);
  @include text-ellipsis(2);
}

.course-progress {
  margin-bottom: 16px;
  
  .progress-info {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    font-size: 14px;
    
    .progress-text {
      color: var(--el-text-color-regular);
    }
    
    .progress-percent {
      color: var(--el-color-primary);
      font-weight: 500;
    }
  }
}

.course-meta {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.course-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.study-plan-section {
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  h2 {
    font-size: 20px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    margin: 0;
  }
}

.study-plans {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.plan-card {
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  padding: 20px;
  
  .plan-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    h4 {
      margin: 0;
      font-size: 16px;
      font-weight: 500;
      color: var(--el-text-color-primary);
    }
  }
  
  .plan-progress {
    margin-bottom: 16px;
    
    .progress-info {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;
      font-size: 14px;
      color: var(--el-text-color-regular);
    }
  }
  
  .plan-actions {
    display: flex;
    gap: 8px;
  }
}

@media (max-width: 768px) {
  .courses-grid {
    grid-template-columns: 1fr;
  }
  
  .study-plans {
    grid-template-columns: 1fr;
  }
}
</style>
